import { _decorator, Component, Collider2D, IPhysics2DContact, Contact2DType, Vec2, RigidBody2D, tween, v3, PhysicsSystem2D, Sprite, color } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('BreakableCollider')
export class BreakableCollider extends Component {
    private originalScale: Vec2 = new Vec2(1, 1);
    private originalPosition: Vec2 = new Vec2(0, 0);
    private isBroken: boolean = false;
    private collider: Collider2D | null = null;
    private sp :Sprite = null;
    
    start() {
        // 保存原始状态
        this.originalScale = new Vec2(this.node.scale.x, this.node.scale.y);
        this.originalPosition = new Vec2(this.node.position.x, this.node.position.y);
        
        this.collider = this.getComponent(Collider2D);
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
        // this.sp = this.getComponent(Sprite);
    }
    
    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 如果已经处于破碎状态，则不再处理
        if (this.isBroken) return;
        
        const otherRigidBody = otherCollider.getComponent(RigidBody2D);
        if (otherRigidBody) {
            // 标记为破碎状态
            this.isBroken = true;
            
            // 开始计时破碎
            this.scheduleOnce(() => {
                this.breakApart();
                
                // 2秒后恢复
                this.scheduleOnce(() => {
                    this.restore();
                    // this.sp.color = color(255,255,255,255);
                }, 2);
                // this.sp.color = color(255,255,255,0);
            }, 2);
        }
    }
    
    breakApart() {
        if (!this.collider) return;
        
        // 禁用碰撞体
        this.collider.enabled = false;
        
        // 破碎动画效果
        tween(this.node)
            .to(0.5, { 
                scale: v3(0, 0, 0), 
                position: v3(this.node.position.x, this.node.position.y - 50, 0) 
            })
            .start();
    }
    
    restore() {
        if (!this.collider) return;
        
        // 恢复碰撞体
        this.collider.enabled = true;
        this.isBroken = false;
        
        // 恢复动画效果
        tween(this.node)
            .to(0.5, { 
                scale: v3(this.originalScale.x, this.originalScale.y, 1),
                position: v3(this.originalPosition.x, this.originalPosition.y, 0)
            })
            .start();
    }
    
    onDestroy() {
        // 清理定时器
        this.unscheduleAllCallbacks();
    }
}